package com.guinea.core.acegi;

import java.io.Serializable;

import org.acegisecurity.GrantedAuthority;
import org.springframework.util.Assert;

public class ResourceDetails implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String resourceString;

	private Long resourceId;

	private GrantedAuthority[] authorities;

	public ResourceDetails(String resString, Long resId, GrantedAuthority[] authorities) {
		if (resString == null || "".equals(resString)) {
			throw new IllegalArgumentException("Cannot pass null or empty values to resource string");
		}
		if (resId == null || "".equals(resId)) {
			throw new IllegalArgumentException("Cannot pass null or empty values to resource ID");
		}
		this.resourceString = resString;
		this.resourceId = resId;
		setAuthorities(authorities);
	}

	public boolean equals(Object rhs) {
		if (!(rhs instanceof ResourceDetails))
			return false;
		ResourceDetails resauth = (ResourceDetails) rhs;
		if (resauth.getAuthorities().length != getAuthorities().length)
			return false;
		for (int i = 0; i < getAuthorities().length; i++) {
			if (!getAuthorities()[i].equals(resauth.getAuthorities()[i]))
				return false;
		}
		return getResourceString().equals(resauth.getResourceString());
	}

	public int hashCode() {
		int code = 168;
		if (getAuthorities() != null) {
			for (int i = 0; i < getAuthorities().length; i++)
				code *= getAuthorities()[i].hashCode() % 7;
		}
		if (getResourceString() != null)
			code *= getResourceString().hashCode() % 7;
		return code;
	}


	public GrantedAuthority[] getAuthorities() {
		return authorities;
	}


	protected void setAuthorities(GrantedAuthority[] authorities) {
		Assert.notNull(authorities, "Cannot pass a null GrantedAuthority array");
		for (int i = 0; i < authorities.length; i++) {
			Assert.notNull(authorities[i],
					"Granted authority element " + i + " is null - GrantedAuthority[] cannot contain any null elements");
		}
		this.authorities = authorities;
	}

	public String getResourceString() {
		return resourceString;
	}

	public void setResourceString(String resourceString) {
		this.resourceString = resourceString;
	}

	public Long getResourceId() {
		return resourceId;
	}

	public void setResourceId(Long resourceId) {
		this.resourceId = resourceId;
	}

}
